﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebUI.BL;
using WebUI.BL.Products;
using WebUI.DAL;

namespace WebUI
{
    /// <summary>
    /// Summary description for JSonHandler
    /// </summary>
    public class JSonHandler : IHttpHandler
    {
        private string keyword;
        public void ProcessRequest(HttpContext context)
        {
            keyword = context.Request.QueryString["keyWord"];
            context.Response.ContentType = "application/json";
            //context.Response.Write(
            //    @"{ ""query"":""Li"", ""suggestions"":[""Liberia"",""Libyan Arab Jamahiriya"",""Liechtenstein"",""Lithuania""], ""data"":[""LR"",""LY"",""LI"",""LT""] }");
            var source = LoadData();
            if(source.Count>0)
            {
                string query = "";
                
                foreach (var tblProductKeyWord in source)
                {

                    query += "{" + String.Format("\"label\":\"{0}\", " + "\"value\":\"{1}\"", tblProductKeyWord.KeyWordVN,tblProductKeyWord.Link) + "},";
                   
                }
                query = query.Substring(0, query.Length - 1);
                string builder = "[ " + query + " ]";
                context.Response.Write(builder);
            }
            else
            {
                context.Response.Write("[ {\"label\":\"Không có dữ liệu\", " + "\"value\":\"null\"} ]");
            }
            
        }

        public List<tbl_ProductKeyWord> LoadData()
        {
            var repository = new ProductKeyWordsBL() ;
            return repository.GetProductkeyWord(keyword).ToList();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}